package edu.xlh.travel.websocket.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.xlh.travel.util.StringUtils;
import edu.xlh.travel.websocket.domin.EmpInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//消息处理类
@Component
public class MyHandler extends TextWebSocketHandler {
    @Autowired
    private RedisTemplate redisTemplate;
    // 在线用户列表
    public volatile static  Map<String, WebSocketSession> userSocketSessionMap = new HashMap<String, WebSocketSession>();
    public volatile static  Map<String, String>  loginedUser= new HashMap<String, String>();

    // 用户连接成功 就被调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //获取传来的登录用户的id
        String currentUserId = session.getUri().toString().split("=")[1];
        if (!currentUserId.equals("undefined") && !StringUtils.isEmpty(currentUserId)) {
            userSocketSessionMap.put(currentUserId, session);
        }
        String webSocketSessionUserId = (String)redisTemplate.opsForValue().get("webSocketSessionUserId");
        int size = userSocketSessionMap.size();
       /* if (!StringUtils.isEmpty(webSocketSessionUserId)
                && (size < 2 )
                && (!userSocketSessionMap.containsKey(webSocketSessionUserId))
        ) {
            //保存对应的WebSocketSession
            userSocketSessionMap.put(webSocketSessionUserId, session);
            loginedUser.put(webSocketSessionUserId , "");
        }*/
        System.err.println("用户连接成功");
    }

    // 消息处理方法
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)  {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            System.out.println("message.getPayload: "+message.getPayload());
            HashMap<String , Object> friendInfo = JSON.parseObject(message.getPayload(), HashMap.class);
            JSONObject data = (JSONObject) friendInfo.get("data");
            JSONObject mine = (JSONObject)data.get("mine");
            JSONObject to = (JSONObject)data.get("to");
            System.out.println(data.get("to"));
            System.out.println(friendInfo.toString());
            //session.sendMessage(message);//发送给当前人
            if(to.get("type").equals("friend")) {
                System.out.println("message payload: "+message.getPayload());
                sendMessageToUser(message , (String)to.get("id"));
            }else if(to.get("type").equals("group")) {
                //sendMessagesToUsers(message,message.getPayload());//给所有的用户发送消息
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 给所有的用户发送消息
     */
    public void sendMessagesToUsers(TextMessage message, EmpInfo friendInfo) {

        Set<String> clientIds  = userSocketSessionMap.keySet();
        WebSocketSession session = null;
        for (String clientId : clientIds) {
            session = userSocketSessionMap.get(clientId);
            System.out.println(clientId);
            try {
                if(session.isOpen()&&!friendInfo.getId().equals(clientId)){
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 给所有的用户发送消息
     */
    public void sendMessageToUser(TextMessage message,String toId) throws IOException {

        Set<String> clientIds  = userSocketSessionMap.keySet();
        //获取userId
        WebSocketSession session = null;
        for (String clientId : clientIds) {
            //根据toId获取session
            if (!toId.equals(clientId)) {
                session = userSocketSessionMap.get(toId);
                System.out.println(session);
                try {
                    if(session.isOpen()){
                        System.out.println("回复消息");
                        System.out.println(message.getPayload());
                        session.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    //用户退出后的处理，退出之后，要将用户信息从websocket的session中remove掉，这样用户就处于离线状态了，也不会占用系统资源
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)  {
        try {
            if(session.isOpen()){
                session.close();
            }
            userSocketSessionMap.remove(session.getId());
            redisTemplate.delete("webSocketSessionUserId");
            System.out.println("退出系统");
        }catch (Exception e){
            System.out.println("用户非正常关闭");
        }


    }

}


